import { ref } from 'vue';

const activeComponent = ref(null);
const handleClickComponent = (e, component) => {
  activeComponent.value = component;
};

// 是否正在拖动的标志
let isDragging = false;
// 鼠标按下事件处理函数
function handleMousedown(e, component) {
  const { currentTarget } = e;
  // 设置拖动标志
  isDragging = true;
  // 保存鼠标点击的位置相对于元素的位置
  const offsetX = e.clientX - parseInt(getComputedStyle(currentTarget).left);
  const offsetY = e.clientY - parseInt(getComputedStyle(currentTarget).top);

  // 鼠标移动事件处理函数
  function mouseMoveHandler(e) {
    if (isDragging) {
      // 更新元素的位置
      component.config.style.left = e.clientX - offsetX;
      component.config.style.top = e.clientY - offsetY;
    }
  }

  // 鼠标抬起事件处理函数
  function mouseUpHandler() {
    // 重置拖动标志并移除事件监听
    isDragging = false;
    document.removeEventListener('mousemove', mouseMoveHandler);
    document.removeEventListener('mouseup', mouseUpHandler);
  }

  // 添加鼠标移动和抬起事件监听
  currentTarget.addEventListener('mousemove', mouseMoveHandler);
  currentTarget.addEventListener('mouseup', mouseUpHandler);
}
export { activeComponent, handleClickComponent, handleMousedown };
